package generation

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/pingcap/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/util/yaml"
	"k8s.io/client-go/dynamic"
)

// ClusterConfig 包含连接集群所需的信息
type ClusterConfig struct {
	Name        string
	Server      string
	BearerToken string
}

func createJob(jenkinsURL, user, apiToken, jobName string, configXML []byte) {
	req, err := http.NewRequest("POST", jenkinsURL+"/createItem?name="+jobName, bytes.NewBuffer(configXML))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/xml")
	req.SetBasicAuth(user, apiToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request to Jenkins:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Println("Failed to create job, status code:", resp.StatusCode)
	} else {
		fmt.Println("Jenkins项目创建成功，地址: http://10.2.4.12:8080/job/" + jobName)
	}
}

func applyYaml(client dynamic.Interface, filename, ns string) error {
	fileBytes, err := os.ReadFile(filename)
	if err != nil {
		return err
	}

	// 将 YAML 转换为 JSON
	jsonBytes, err := yaml.ToJSON(fileBytes)
	if err != nil {
		return err
	}

	// 解析 JSON 到 unstructured.Unstructured
	obj := &unstructured.Unstructured{}
	_, _, err = unstructured.UnstructuredJSONScheme.Decode(jsonBytes, nil, obj)
	if err != nil {
		return err
	}

	// 获取资源信息
	gvk := obj.GroupVersionKind()
	gvr, _ := meta.UnsafeGuessKindToResource(gvk)
	resourceClient := client.Resource(gvr).Namespace(ns)

	// 尝试创建资源
	_, err = resourceClient.Create(context.Background(), obj, metav1.CreateOptions{})
	if err != nil {
		// 检查资源是否已存在
		if errors.IsAlreadyExists(err) {
			fmt.Printf("Resource from %s already exists, skipping...\n", filename)
			return nil
		}
		return err
	}

	fmt.Printf("Applied %s\n", filename)
	return nil
}
